package com.soo.hoo.admin.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.soo.hoo.admin.model.dto.FileDTO;
import com.soo.hoo.admin.model.entity.SysUserFamily;
import com.soo.hoo.admin.model.vo.UserVO;
import com.soo.hoo.admin.service.UserFamilyService;
import com.soo.hoo.admin.service.UserService;
import com.soo.hoo.core.model.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>移动端授权管理</p>
 *
 * @author 杨燚
 * @since 2023/7/7
 */
@Tag(name = "App端授权控制")
@RequestMapping("/app/")
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AppAuthController {


    private final WxMaService wxMaService;
    private final UserService userService;
    private final UserFamilyService userFamilyService;


    @Operation(summary = "微信小程序手机号一键登录")
    @GetMapping("wxLogin")
    @SneakyThrows(WxErrorException.class)
    public Result<UserVO> wxLogin(@RequestParam String code) {
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(code);
        UserVO vo = userService.login(phoneNoInfo.getPhoneNumber());
        SysUserFamily family = userFamilyService.getFamily(StpUtil.getLoginIdAsLong());
        vo.setFamilyId(family == null ? "" : family.getFamilyId());
        return Result.success(vo);
    }

    @Operation(summary = "微信小程序退出登录")
    @GetMapping("wxLogout")
    public Result<Void> wxLogout(@RequestParam Long userId) {
        userService.logout(userId);
        return Result.success();
    }
}
